package com.tree.common.aop;

import com.tree.common.util.UserContextHolder;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @ClassName com.demo.common.aop
 * Description: <类功能描述>. <br>
 * <p>
 * <使用说明>
 * </p>
 * @Author tree
 * @Date 2019-05-24 23:02
 * @Version 1.0
 */
@Aspect
@Component
public class OperatorAop {
    private static final String CREATER_ID = "creater_Id";
    private static final String MODIFIER_ID = "modifier_Id";
    private static final String CREATE_TIME = "create_time";
    private static final String MODIFY_TIME = "update_time";

    @Before("execution(* com.tree.mybatisplus.**.insert*(..))")
    private void beforeAddAdvice(JoinPoint jp){
        Object[] args = jp.getArgs();
        if(args != null && args.length > 0){
            Object arg = args[0];
            long userId = UserContextHolder.getUserInfo().getId();
            BeanWrapper beanWrapper = new BeanWrapperImpl(arg);
            if(beanWrapper.isWritableProperty(CREATER_ID)){
                beanWrapper.setPropertyValue(CREATER_ID,userId);
            }
            if(beanWrapper.isWritableProperty(MODIFIER_ID)){
                beanWrapper.setPropertyValue(MODIFIER_ID,userId);
            }
            if(beanWrapper.isWritableProperty(CREATE_TIME)){
                beanWrapper.setPropertyValue(CREATE_TIME,new Date());
            }
            if(beanWrapper.isWritableProperty(MODIFY_TIME)){
                beanWrapper.setPropertyValue(MODIFY_TIME,new Date());
            }
        }
    }

    @Before("execution(* com.tree.**.update*(..))")
    private void beforeUpdateAdvice(JoinPoint jp){
        Object[] args = jp.getArgs();
        if(args != null && args.length > 0){
            Object arg = args[0];
            long userId = UserContextHolder.getUserInfo().getId();
            BeanWrapper beanWrapper = new BeanWrapperImpl(arg);
            if(beanWrapper.isWritableProperty(MODIFIER_ID)){
                beanWrapper.setPropertyValue(MODIFIER_ID,userId);
            }
            if(beanWrapper.isWritableProperty(MODIFY_TIME)){
                beanWrapper.setPropertyValue(MODIFY_TIME,new Date());
            }
        }
    }
}
